package com.v1.video.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.common.http.basecore.utils.LogInfo;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.activity.ChannelManagerActivity2;
import com.v1.video.activity.WebViewActivity3;
import com.v1.video.db.service.StatisticsDB;
import com.v1.video.domain.Channel;
import com.v1.video.domain.ChannelEntity;
import com.v1.video.domain.CustomChannelLst;
import com.v1.video.domain.MaiPaigeLiveInfo;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.interfaces.OnChannelListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utility;
import com.v1.video.util.Utils;
import com.v1.video.view.PagerSlidingTabStrip;
import com.v1.video.view.PagerSlidingTabStrip.OnTabPageSelected;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页分类
 * 
 * @author wangfang
 * 
 */
public class MainPageHeadlineFragment extends V1BaseFragment implements
		IRefresh, OnClickListener {
	private static final String TAG = "MainPageHeadlineFragment";
	private static final int REQUEST_CODE = 100;
	private static final int RECOMMEND_POSITION = 0;
	private static final int REFRESH = 200;
	private LayoutInflater mInflater;
	private View mRootView;
	private PagerSlidingTabStrip mPagerTab;
	private ViewPager mViewPager;
	private PageTabAdapter mPageTabAdapter;
	private ImageView mIvAdd;
	private List<Channel> mChannelLst;
	private List<Channel> mOtherChannelLst;
	private ImageView mIvLive;
	private MaiPaigeLiveInfo mLiveInfo;
	private int mCurIndex = -1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		mRootView = mInflater.inflate(R.layout.fragment_main_page_headline,
				container, false);
		initView();
		setListener();
		initData();
		return mRootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("首页");
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("首页");
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (hidden) {
			releasePlayer();
		}
	}

	private void initView() {
		MobclickAgent.onEvent(this.getActivity(), Constant.HOME_ID);
		mPagerTab = (PagerSlidingTabStrip) mRootView
				.findViewById(R.id.tab_topline);
		mViewPager = (ViewPager) mRootView.findViewById(R.id.vp_viewpager);
		mIvAdd = (ImageView) mRootView.findViewById(R.id.iv_add);
		mIvLive = (ImageView) mRootView.findViewById(R.id.iv_live);
		mPagerTab.setTextSize(17);
		mPagerTab.setSeltabTextSize(19);
	}

	private void setListener() {
		mIvAdd.setOnClickListener(this);
		mIvLive.setOnClickListener(this);
	}

	private void initData() {
		mLiveInfo = AppContext.getInstance().getLiveInfo();
		if (mLiveInfo != null && TextUtils.isEmpty(mLiveInfo.getStatus())) {
			if ("1".equals(mLiveInfo.getStatus())) {
				ImageLoader.getInstance().displayImage(mLiveInfo.getPic(),
						mIvLive, Constant.LIVE_HEAD_IMG, null);
				mIvLive.setVisibility(View.VISIBLE);
			} else {
				mIvLive.setVisibility(View.GONE);
			}
		} else {
			mIvLive.setVisibility(View.GONE);
		}
		loadCachedData();
		if (Helper.checkConnection(getActivity())) {
			getServerData();
		} else {
			getLocalData();
			Toast.makeText(getActivity(),
					getResources().getString(R.string.net_no_notclick),
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 初始化频道栏目
	 */
	private void showPageTabView() {
		if (mChannelLst != null && mChannelLst.size() > 0) {
			mPageTabAdapter = new PageTabAdapter(this.getActivity()
					.getSupportFragmentManager());

			mPagerTab.setOnTabPageSelected(new OnTabPageSelected() {

				@Override
				public void onTabPageSelected(int position) {
					// TODO Auto-generated method stub
					mCurIndex = position;
					refreshFragment();
				}
			});
			mPageTabAdapter.setFragments(createFragment(mChannelLst));
			mViewPager.setAdapter(mPageTabAdapter);
			mPagerTab.setViewPager(mViewPager);
		}
	}

	/**
	 * 创建Fragment页面
	 * 
	 * @param channelLst
	 * @return
	 */
	private List<Fragment> createFragment(List<Channel> channelLst) {
		if (channelLst != null && channelLst.size() > 0) {
			List<Fragment> fragments = new ArrayList<Fragment>();
			for (int i = 0; i < channelLst.size(); i++) {
				Channel channel = channelLst.get(i);
				if (channel != null) {
					if (i == RECOMMEND_POSITION) {
						RecommendFragment fragment = RecommendFragment
								.newInstance(channel.getCid());
						fragments.add(fragment);
						fragment.setOnChannelListener(new OnChannelListener() {

							@Override
							public void onChannelListener(String cid,
									String ctype) {
								// TODO Auto-generated method stub
								if (!TextUtils.isEmpty(cid)) {
									changeFragment(cid, ctype);
								}
							}
						});
					} else if ("1".equals(channel.getCtype())) {
						fragments
								.add(CibnFragment.newInstance(channel.getCid(),channel.getGenre()));
					}else if(channel.getCid().equals("30")){
							fragments
							.add(MainPageBuddhismFragment.newInstance(channel.getCid(),channel.getGenre()));
							
					} else {
						fragments.add(ClassifyFragment.newInstance(
								channel.getCid(), channel.getType()));
					}
				}
			}
			return fragments;
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_add:
			Intent intent = new Intent();
			intent.setClass(this.getActivity(), ChannelManagerActivity2.class);
			intent.putExtra("Index", mViewPager.getCurrentItem());
			startActivityForResult(intent, REQUEST_CODE);
			break;
		case R.id.iv_live:
			if (mLiveInfo != null) {
				Intent inLive = new Intent();
				// inLive.setClass(this.getActivity(), WebViewActivity2.class);
				inLive.setClass(this.getActivity(), WebViewActivity3.class);
				inLive.putExtra("adLink", mLiveInfo.getUrl());
				inLive.putExtra(WebViewActivity3.FLAG_TYPE,
						WebViewActivity3.STATE_TYPE_1);
				startActivity(inLive);
			}
			break;
		default:
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case REFRESH:
				mCurIndex = (Integer) msg.obj;
				if (mViewPager != null) {
					mViewPager.setCurrentItem(mCurIndex);
				}
				// refreshFragment();
				break;
			default:
				break;
			}
		}

	};
	
	/**
	 * 切换Fragment
	 */
	private void changeFragment(String cid, String ctype) {
		if (mChannelLst != null && mChannelLst.size() > 0) {
			for (int i = 0; i < mChannelLst.size(); i++) {
				Channel channel = mChannelLst.get(i);
				if (channel != null && cid.equals(channel.getCid())) {
					Message msg = mHandler.obtainMessage();
					msg.what = REFRESH;
					msg.obj = i;
					mHandler.sendMessage(msg);
					break;
				}
			}
		}
	}

	/**
	 * 刷新Fragment
	 */
	private void refreshFragment() {
		if (mPageTabAdapter != null
				&& mPageTabAdapter.getFragments().size() > mCurIndex) {
			Fragment mFragment = mPageTabAdapter.getFragments().get(mCurIndex);
			Channel channel = mChannelLst.get(mCurIndex);
			if (mFragment != null) {
				if (mCurIndex == RECOMMEND_POSITION) {
					((RecommendFragment) mFragment).refresh(null);
				} else if (channel != null && "1".equals(channel.getCtype())) {
					((CibnFragment) mFragment).refresh(null);
				}else if(channel.getCid().equals("30")){
					((MainPageBuddhismFragment) mFragment).refresh(null);
				} else {
					((ClassifyFragment) mFragment).refresh(null);
				}
			}
		}
	}

	/**
	 * 释放当前播放器
	 */
	private void releasePlayer() {
		if (mCurIndex != -1 && mCurIndex != RECOMMEND_POSITION) {
			if (mPageTabAdapter != null
					&& mPageTabAdapter.getFragments().size() > mCurIndex) {
				Fragment mFragment = mPageTabAdapter.getFragments().get(
						mCurIndex);
				if (mFragment != null && mFragment instanceof ClassifyFragment) {
					((ClassifyFragment) mFragment).releasePlayer();
				}
			}
		}
	}

	/**
	 * 加载本地数据
	 */
	private void getLocalData() {
		if (mChannelLst != null && mChannelLst.size() > 0) {
			createFragment(mChannelLst);
			showPageTabView();
		}
	}

	/**
	 * 加载本地缓存数据
	 */
	private void loadCachedData() {
		String json = Utility.ReadTxtFile(getActivity(),
				"CustomChannelCache.txt");
		if (!TextUtils.isEmpty(json)) {
			Gson gson = new Gson();
			CustomChannelLst mCustomChannelLst = gson.fromJson(json,
					CustomChannelLst.class);
			mChannelLst = mCustomChannelLst.getUserLst();
			mOtherChannelLst = mCustomChannelLst.getOtherLst();
		}
	}

	/**
	 * 获取服务器数据
	 */
	private void getServerData() {
		String url = String.format(Constant.HOME_CHANNEL_LIST,
				Constant.PRODUCT_CODE, Constant.PRODUCT_VERSION);
		LogInfo.log("haitian",  "频道列表url=" + url);
		RequestManager.getInstance().getRequest(this.getActivity(), url,
				ChannelEntity.class, null, new OnResponseListener() {
					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						if (object != null) {
							ChannelEntity entity = (ChannelEntity) object;
							if (entity != null && entity.getHeader() != null
									&& entity.getBody() != null) {
								if (!TextUtils.isEmpty(entity.getHeader()
										.getMarkid())) {
									String valueStr = AppContext.getInstance()
											.getMemeryCache().get(keyId);
									if (TextUtils.isEmpty(valueStr)
											|| !valueStr.equals(entity
													.getHeader().getMarkid())) {
										syncChannelData(entity.getBody()
												.getData(), keyId, entity
												.getHeader().getMarkid());
									} else {
										getLocalData();
									}
								} else {
									getLocalData();
								}
							} else {
								getLocalData();
							}
						} else {
							getLocalData();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Toast.makeText(getActivity(), message,
								Toast.LENGTH_SHORT).show();
						Logger.i(TAG, message);
						getLocalData();
					}

				});
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CODE:
			if (resultCode == this.getActivity().RESULT_OK) {
				boolean isOperate = data.getBooleanExtra("isSort", false);
				int Index = data.getIntExtra("Index", 0);
				if (isOperate == true) {
					mChannelLst = (List<Channel>) data
							.getSerializableExtra("userChannel");
					if (mPageTabAdapter != null) {
						mPageTabAdapter
								.setFragments(createFragment(mChannelLst));
					}
					if (mPagerTab != null) {
						mPagerTab.notifyDataSetChanged();
					}
					Message msg = mHandler.obtainMessage();
					msg.what = REFRESH;
					msg.obj = Index;
					mHandler.sendMessageDelayed(msg, 500);
				} else {
					if (mViewPager != null) {
						mViewPager.setCurrentItem(Index);
					}
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 频道数据同步
	 * 
	 * @param mLst
	 * @param keyId
	 * @param markId
	 */
	private void syncChannelData(List<Channel> mLst, String keyId, String markId) {
		try {
			if (mLst != null && mLst.size() > 0) {
				AppContext.getInstance().getMemeryCache().putDB(keyId, markId);
				if (Utils.getChannelOperate(this.getActivity())) {
					List<Channel> mLstData = new ArrayList<Channel>();
					if (mChannelLst != null && mChannelLst.size() > 0) {
						mLstData.addAll(mChannelLst);
					}
					if (mOtherChannelLst != null && mOtherChannelLst.size() > 0) {
						mLstData.addAll(mOtherChannelLst);
					}
					if (mLstData != null && mLstData.size() > 0) {
						List<Channel> mRemoveLst = new ArrayList<Channel>();
						for (int i = 0; i < mLstData.size(); i++) {
							Channel mChannel = mLstData.get(i);
							boolean flag = false;
							for (int j = 0; j < mLst.size(); j++) {
								Channel mChannel2 = mLst.get(j);
								if (mChannel2.getCid()
										.equals(mChannel.getCid())) {
									if (mChannelLst.size() > i) {
										mChannelLst.get(i).setName(
												mChannel2.getName());
										mChannelLst.get(i).setType(
												mChannel2.getType());
									} else {
										mOtherChannelLst.get(
												i - mChannelLst.size())
												.setName(mChannel2.getName());
										mOtherChannelLst.get(
												i - mChannelLst.size())
												.setType(mChannel2.getType());
									}
									mLst.remove(mChannel2);
									flag = true;
									break;
								}
							}
							if (flag == false) {
								mRemoveLst.add(mChannel);
							}
						}
						if (mRemoveLst != null && mRemoveLst.size() > 0) {
							for (int i = 0; i < mRemoveLst.size(); i++) {
								Channel mChannel = mRemoveLst.get(i);
								if (mChannelLst.contains(mChannel)) {
									mChannelLst.remove(mChannel);
								}
								if (mOtherChannelLst != null
										&& mOtherChannelLst.size() > 0) {
									if (mOtherChannelLst.contains(mChannel)) {
										mOtherChannelLst.remove(mChannel);
									}
								}
							}
						}
						if (mLst.size() > 0) {
							for (int k = 0; k < mLst.size(); k++) {
								Channel mChannel = mLst.get(k);
								int index = mChannel.getSort() - 1;
								if (mChannel.getSort() > index) {
									mChannelLst.add(mChannel);
								} else {
									mChannelLst.add(index, mChannel);
								}
							}
						}
						// mChannelLst.get(0).setFlag(1);
					} else {
						mChannelLst = mLst;
						// mChannelLst.get(0).setFlag(1);
						StatisticsDB.getInstance().insertInTx(mChannelLst);
					}
				} else {
					mChannelLst = mLst;
					StatisticsDB.getInstance().insertInTx(mChannelLst);
				}
				showPageTabView();
				CustomChannelLst mCusLst = new CustomChannelLst();
				mCusLst.setUserLst(mChannelLst);
				if (mOtherChannelLst != null && mOtherChannelLst.size() > 0) {
					mCusLst.setOtherLst(mOtherChannelLst);
				}
				Gson gson = new Gson();
				String jsonStr = gson.toJson(mCusLst);
				Utility.CacheData(this.getActivity(), "CustomChannelCache.txt",
						jsonStr);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class PageTabAdapter extends FragmentStatePagerAdapter {

		private List<Fragment> mFragments;

		public PageTabAdapter(FragmentManager fm) {
			super(fm);
			this.mFragments = new ArrayList<Fragment>();
		}

		public void setFragments(List<Fragment> fragments) {
			if (fragments != null && fragments.size() > 0) {
				this.mFragments = fragments;
				this.notifyDataSetChanged();
			}
		}

		public List<Fragment> getFragments() {
			return this.mFragments;
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return mChannelLst.get(position).getName();
		}

		@Override
		public Fragment getItem(int position) {
			return mFragments.get(position);
		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return POSITION_NONE;
		}
	}
}
